<?php

class EmbeddedTentValidatorSchema extends sfValidatorSchema
{
  const OPTION_ALLOW_EMPTY = 'allow_empty';

  protected function configure ($options = array(), $messages = array())
  {
    $this->addOption(self::OPTION_ALLOW_EMPTY, false);
  }

  protected function doClean ($values)
  {
    $empty_forms = 0;
    $allow_empty_forms = $this->getOption(self::OPTION_ALLOW_EMPTY);
    
    $errorSchema = new sfValidatorErrorSchema($this);
    $defaultMessages = array('required' => 'Pflichtfeld', 'invalid' => 'Ungültig');
    $validatorSchema = array(
	  'type'       => new sfValidatorChoice(array('choices' => array(0 => 'a', 1 => 'k', 2 => 'j', 3 => 'h'), 'required' => true), $defaultMessages),
      'capacity'   => new sfValidatorInteger(array('required' => true, 'min' => 1), $defaultMessages)
    );
    
    foreach ($values as $key => $value)
    {
      
      $localErrorSchema = new sfValidatorErrorSchema($this);
      
      if (! $value['type'] && ! $value['capacity'])
      {
        if ($allow_empty_forms == false || $empty_forms >= $allow_empty_forms)
        {
          unset($values[$key]);
        }
        else
        {
          $empty_forms ++;
          unset($values[$key]);
        }
      }
      else
      {
        if(is_array($value)) {
          foreach($value as $field => $field_value) {
            try {
              if(isset($validatorSchema[$field])) {
                $validatorSchema[$field]->clean($field_value);
              }
            } catch(sfValidatorError $error) {
              $localErrorSchema->addError($error, $field);
            }
          }
        }
//        if (! $value['type'])
//        {
//          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'type');
//        }
//        if (! $value['capacity'])
//        {
//          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'capacity');
//        }
      }
      
      if (count($localErrorSchema))
      {
        $errorSchema->addError($localErrorSchema, (string) $key);
      }
    }
    
    if (count($errorSchema))
    {
      throw new sfValidatorErrorSchema($this, $errorSchema);
    }
    
    return $values;
  }
}